package com.xhtt.fzxy.console;

import net.lastcoder.ifserver.database.DBHelper;
import net.lastcoder.ifserver.plugin.Plugin;
import net.lastcoder.ifserver.plugin.PluginManager;

import org.apache.tomcat.InstanceManager;
import org.apache.tomcat.SimpleInstanceManager;
import org.eclipse.jetty.apache.jsp.JettyJasperInitializer;
import org.eclipse.jetty.plus.annotation.ContainerInitializer;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.BaseHolder;
import org.eclipse.jetty.servlet.ServletHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.servlet.ServletMapping;
import org.eclipse.jetty.webapp.WebAppContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.Arrays;
import java.util.EnumSet;

import javax.servlet.DispatcherType;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**web控制台
 * auth: WenYF
 * date: 2018/5/4
 */
public class WebConsolePlugin implements Plugin {
    public static final Logger Log = LoggerFactory.getLogger(WebConsolePlugin.class);

    private Server server;
    public static WebConsolePlugin instance;
    
    public static WebConsolePlugin getInstance() {
        return instance;
    }
    
    private class LocalWebContext extends WebAppContext {
        @Override
        public void doHandle(String target, Request baseRequest, HttpServletRequest request
                , HttpServletResponse response) throws IOException, ServletException {
            Log.info("path:" + target);
            Log.info("request:" + baseRequest.toString());
            Log.info("servlet request:" + request);
            Log.info("servlet respone:" + response);
            super.doHandle(target, baseRequest, request, response);
        }
    }
    
    @Override
    public void initializePlugin(PluginManager manager, File pluginDirectory) {
        System.out.println("start fzxyweb initializePlugin...");
        instance = this;
        
        // 初始化数据库链接
        // DBHelper.init();
        
        WebAppContext handler = null;
        String dir = "";
        if (Boolean.getBoolean("local")) {
            // TODO 改为你的目录
            dir = "E:\\Ifserver\\src\\resource\\web";
        } else {
            dir = net.lastcoder.ifserver.Globals.getHomeDirectory() + File.separator + "resource"
                    + File.separator + "web";
        }
        handler = new WebAppContext(dir, "/");
        handler.setDefaultsDescriptor(dir + File.separator + "webdefault.xml");
        handler.setDescriptor(dir + File.separator + "WEB-INF" + File.separator + "web.xml");
        File tmpFile = new File(dir + File.separator + "tmpFile");
        if (!tmpFile.exists()) {
            tmpFile.mkdirs();
        }
        // JSP 相关
        handler.setTempDirectory(tmpFile);
        handler.setAttribute("javax.servlet.context.tempdir", tmpFile);
        // 下面是为解决此次问题增加的代码
        handler.setAttribute("org.eclipse.jetty.containerInitializers" , Arrays.asList (
                new ContainerInitializer(new JettyJasperInitializer(), null)));
        handler.setAttribute(InstanceManager.class.getName(), new SimpleInstanceManager());
        
        InetSocketAddress address = new InetSocketAddress("0.0.0.0", 6000);

        server = new Server(address);
        server.setHandler(handler);
        try {
            server.start();
        } catch (Exception e) {
            Log.error(e.getMessage(), e);
        }

        System.out.println("fzxyweb initializePlugin success.");

        // 设置servlet
        ServletHandler servletHandler = handler.getServletHandler();
        ServletHolder holder = servletHandler.newServletHolder(BaseHolder.Source.EMBEDDED);
        holder.setName("ConsoleServlet");
        holder.setServlet(new ConsoleServlet());
        holder.setClassName(ConsoleServlet.class.getName());
        servletHandler.addServlet(holder);
        ServletMapping servletMapping = new ServletMapping();
        servletMapping.setServletName("ConsoleServlet");
        servletMapping.setPathSpec("/fzxy/*");
        servletHandler.addServletMapping(servletMapping);
        
        // 设置鉴权filter
        EnumSet enumSet = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD);
        handler.addFilter(AuthFilter.class, "*", enumSet);
    }

    @Override
    public void destroyPlugin() {
        System.out.println("start fzxyweb destroyPlugin...");

        try {
            server.stop();
        } catch (Exception e) {
            Log.error(e.getMessage(), e);
        }

        System.out.println("end fzxyweb destroyPlugin.");

        instance = null;
    }
    
    public String getConsoleName() {
        return "某某软件后台";
    }

    public String getDeployName() {
        return "测试服";
    }
}
